package com.zbkj.crmeb.order.channel;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import com.zbkj.crmeb.plat.by.dto.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.crmeb.core.common.CommonResult;
import com.crmeb.core.config.RestTemplateConfig;
import com.zbkj.crmeb.enums.BarCodeEnum;
import com.zbkj.crmeb.enums.PurchaseOrderChannelTypeEnum;
import com.zbkj.crmeb.order.AbstractStoreOrderService;
import com.zbkj.crmeb.order.StoreOrderFactory;
import com.zbkj.crmeb.order.request.EfasionOrderRequest;
import com.zbkj.crmeb.order.request.EfasionOrderRequest.OutOrderInfoRequest;
import com.zbkj.crmeb.store.dao.StoreOrderDao;
import com.zbkj.crmeb.store.model.StoreOrder;
import com.zbkj.crmeb.store.model.StoreProduct;
import com.zbkj.crmeb.store.model.StoreProductAttrValue;
import com.zbkj.crmeb.store.service.StoreProductAttrValueService;
import com.zbkj.crmeb.store.service.StoreProductService;
import com.zbkj.crmeb.store.vo.StoreOrderInfoVo;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class EfasionStoreOrderServiceImpl extends AbstractStoreOrderService {
    @Resource
    private StoreOrderDao storeOrderDao;
    @Autowired
    private RestTemplateConfig restTemplateConfig;
    @Autowired
    private StoreProductAttrValueService storeProductAttrValueService;
    @Autowired
    private StoreProductService storeProductService;
    @Autowired
    private StoreOrderFactory storeOrderFactory;
    
    /********* 配置参数  *********/
    @Value("${efasion.url.domain}")
    private String domainUrl;
    @Value("${efasion.url.orderPush}")
    private String orderPushUrl;
    @Value("${efasion.appkey}")
    private String appKey;
    @Value("${efasion.secret}")
    private String secret;

    @Override
    public CommonResult<Object> addChannelOrder(StoreOrder storeOrder, List<StoreOrderInfoVo> orderInfoVoList) {
        List<String> errorMessages = new ArrayList<>();
        try {
        	for(StoreOrderInfoVo order : orderInfoVoList) {
                String barCode = order.getInfo().getProductInfo().getBarCode();
                String sourceSkuId = order.getInfo().getProductInfo().getAttrInfo().getSourceSkuId();
                StoreProductAttrValue value = storeProductAttrValueService.getOne(Wrappers.<StoreProductAttrValue>lambdaQuery()
                        .eq(StoreProductAttrValue :: getBarCode, barCode)
                        .eq(StoreProductAttrValue :: getSourceSkuId, sourceSkuId)
                        .last("LIMIT 1")
                        );
                if(null == value) {
                	log.error("--------------- 订单推送至efasion异常, 当前商品规格不存在: {}", sourceSkuId);
                	continue;
                }
                StoreProduct storeProduct = storeProductService.getById(value.getProductId());
                if(9 != storeOrder.getSource()) {
                    storeOrder.setPushOrderNo(order.getChildOrderNumber());
                }
                // 组建订单对象
                EfasionOrderRequest efasionOrderRequest = new EfasionOrderRequest();
                efasionOrderRequest.setOrderId(storeOrder.getPushOrderNo());
                efasionOrderRequest.setRealName(storeOrder.getRealName());
                efasionOrderRequest.setUserPhone(storeOrder.getUserPhone());
                efasionOrderRequest.setProvince(storeOrder.getProvince());
                efasionOrderRequest.setCity(storeOrder.getCity());
                efasionOrderRequest.setDistrict(storeOrder.getDistrict());
                efasionOrderRequest.setDetail(storeOrder.getDetail());
                // 组装商品信息
                List<OutOrderInfoRequest> outOrderInfoRequests = new ArrayList<>();
                OutOrderInfoRequest outOrderInfoRequest = new OutOrderInfoRequest();
                outOrderInfoRequest.setProductId(Integer.parseInt(storeProduct.getBarCode().replaceFirst(BarCodeEnum.EFASION.getCode()+"", "")));
                outOrderInfoRequest.setSourceSkuId(sourceSkuId.replaceFirst(storeProduct.getIsEurope() + "-", ""));
                outOrderInfoRequest.setCartNum(1);
                outOrderInfoRequest.setPrice(value.getPrice());
                outOrderInfoRequests.add(outOrderInfoRequest);
                efasionOrderRequest.setOutOrderInfoRequest(outOrderInfoRequests);
                // 推送
                Result result = pushOrder(storeOrder, efasionOrderRequest, order);
                if(!result.isSuccess()){
                    errorMessages.add("订单号: " + order.getOrderInfoId() + ",错误: " + result.getMessage());
                }
            }
        	
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (!errorMessages.isEmpty()) {
            return CommonResult.failed(String.join("\n", errorMessages));
        }
        return CommonResult.success();
    }


    /**
     * 获取buyer商品数据和详情
     * @Description:
     * @author daigb
     * @param @param id 商品barCode
     * @param @return
     * @param @throws Exception
     * @return BuyerProductResDTO
     * @throws
     */
    private Result pushOrder(StoreOrder storeOrder, EfasionOrderRequest request, StoreOrderInfoVo orderInfo) {
//    	String orderId = storeOrder.getSource() == 9 ? storeOrder.getOrderId().split("-")[0] : storeOrder.getOrderId();
        // 组装请求url
        StringBuilder sb = new StringBuilder();
        sb.append(domainUrl);
        sb.append(orderPushUrl);
        // 发送请求
        RestTemplate restTemplate = restTemplateConfig.restTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.add("appKey", appKey);
        headers.add("secret", secret);
        HttpEntity<String> formEntity = new HttpEntity<>(JSON.toJSONString(request), headers);
        ResponseEntity<String> response = restTemplate.postForEntity(sb.toString(), formEntity , String.class);

        if (HttpStatus.OK != response.getStatusCode()) {
            JSONObject message = JSONObject.parseObject(response.getBody());
            String errorMessage = message.getString("error");

            log.info("--------------- EFASION订单{} ---------------", errorMessage);
            return new Result(false, null, errorMessage);
        }
        JSONObject responseData = JSONObject.parseObject(response.getBody());
        Integer status = responseData.getInteger("code");
        String message = responseData.getString("message");
        if(HttpStatus.OK.value() == status) {
            //新增采购单
            storeOrderFactory.insertPurchaseOrder(storeOrder, true, PurchaseOrderChannelTypeEnum.EFASION.getCode());
            //新增采购商品
            storeOrderFactory.insertPurchaseGoods(orderInfo, storeOrder, true, "成功", null);
            if(storeOrder.getPushStatus() != 2){
        		StoreOrder storeOrderUpdate = new StoreOrder();
        		storeOrderUpdate.setId(storeOrder.getId());
        		storeOrderUpdate.setPushStatus(1);
        		storeOrderUpdate.setPushMessage(message);
                storeOrderDao.updateById(storeOrderUpdate);
            }
            
            log.info("--------------- EFASION订单推送成功 ---------------");
            return new Result(true, status.toString(), message);
        } else {
            //新增采购单
        	storeOrderFactory.insertPurchaseOrder(storeOrder, false, PurchaseOrderChannelTypeEnum.EFASION.getCode());
            //新增采购商品
        	storeOrderFactory.insertPurchaseGoods(orderInfo, storeOrder, false, "失败", null);
    		StoreOrder storeOrderUpdate = new StoreOrder();
    		storeOrderUpdate.setId(storeOrder.getId());
    		storeOrderUpdate.setPushStatus(2);
    		storeOrderUpdate.setPushMessage(message);
            storeOrderDao.updateById(storeOrderUpdate);
            log.info("--------------- EFASION订单推送失败: {} ---------------", responseData.toJSONString());
            return new Result(false, status.toString(), message);
        }
    
    }

    @Override
    public CommonResult<Object> cancelChannelOrder(StoreOrder storeOrder, List<StoreOrderInfoVo> orderInfoVoList) {
        return null;
    }

    @Override
    public CommonResult<Object> getOrderInfo(String channelOrderSn) {
        return null;
    }

}
